package com.fj.shiro;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fj.entity.User;
import com.fj.handler.BusinessException;
import com.fj.response.ResultCode;
import com.fj.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author mo
 * @Description: 自定义认证及鉴权处理器
 * @date 2020-09-22 15:13
 */

public class MyRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }

    /**
     * 此期没有涉及到用户的角色，所只不需要实现鉴权
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    /**
     * 默认使用此方法进行用户正确与否验证，错误抛出异常即可
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String token = (String) authenticationToken.getCredentials();
        if (token == null) {
            throw new BusinessException(ResultCode.AUTH_TOKEN_IS_EMPTY.getCode(),
                    ResultCode.AUTH_TOKEN_IS_EMPTY.getMessage());
        }
        // 解密获得username，用于和数据库进行对比
        String username = JWTUtil.getUsername(token);
        if (username == null) {
            throw new BusinessException(ResultCode.USER_ACCOUNT_NOT_EXIST.getCode(),
                    ResultCode.USER_ACCOUNT_NOT_EXIST.getMessage());
        }
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUserName,username);
        User user = userService.getOne(wrapper);
        if (user == null) {
            throw new BusinessException(ResultCode.USER_CREDENTIALS_ERROR.getCode(),
                    ResultCode.USER_CREDENTIALS_ERROR.getMessage());
        }

        if (!JWTUtil.verify(token, username, user.getUserPassword())) {
            throw new BusinessException(ResultCode.USER_CREDENTIALS_ERROR.getCode(),
                    ResultCode.USER_CREDENTIALS_ERROR.getMessage());
        }
        return new SimpleAuthenticationInfo(token, token, "my_realm");
    }

}
